﻿using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClsController
{
    class EjemploThreadPool
    {

        private const int NumThreads = 20;

        private static int[] inputArray;
        private static double[] resultArray;
        private static ManualResetEvent[] resetEvents;

        private static void Main(string[] args)
        {
            ArrayList listado = new ArrayList();
            inputArray = new int[NumThreads];
            resultArray = new double[NumThreads];
            resetEvents = new ManualResetEvent[NumThreads];

            Random rand = new Random();
            for (int s = 0; s < NumThreads; s++)
            {
                listado = new ArrayList();
                listado.Add("SOY" + s.ToString());
                listado.Add(s);
                inputArray[s] = rand.Next(1, 5000000);
                resetEvents[s] = new ManualResetEvent(false);
                ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), (object)listado);
            }
            Console.WriteLine("Waiting...");

            WaitHandle.WaitAll(resetEvents);

            Console.WriteLine("And the answers are: ");
            for (int i = 0; i < NumThreads; i++)
                Console.WriteLine(inputArray[i] + " -> " + resultArray[i]);
            Console.Read();
        }

        /* private static void DoWork(object o)
         {
             int index = (int)o;

             for (int i = 1; i < inputArray[index]; i++)
                 resultArray[index] += 1.0 / (i * (i + 1));

             resetEvents[index].Set();
         }*/

        private static void DoWork(object o)
        {
            ArrayList index = (ArrayList)o;
            int valor = (int)index[3];

            for (int i = 1; i < inputArray[valor]; i++)
                resultArray[valor] += 1.0 / (i * (i + 1));

            resetEvents[valor].Set();
        }
    }
}
